//
//  ShopListViewController.m
//  rrbi
//
//  Created by mac book on 2018/12/4.
//

#import "ShopListViewController.h"
#import "ShopListTableViewCell.h"


@interface ShopListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;

@property(nonatomic,strong) NetPage* page;


@end

@implementation ShopListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.navigationItem.title =  @"店铺分类";
//    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    rightButton.backgroundColor = [UIColor greenColor];
//    rightButton.layer.cornerRadius = 5;
//    rightButton.frame = CGRectMake(0, 0, 60, 25);
//    [rightButton setTitle:@"添加分类" forState:UIControlStateNormal];
//    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    rightButton.titleLabel.font = kFontNameSize(14);
//    [rightButton addTarget:self action:@selector(rightButton) forControlEvents:UIControlEventTouchUpInside];
//    //添加到导航条
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(rightButton)];

    [self creatSubViews];
    
    [self refreshDataSource];
}

-(void)rightButton{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"添加分类" preferredStyle:UIAlertControllerStyleAlert];
    //定义第一个输入框；
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入分类名";
        
    }];
    //增加取消按钮；
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        UITextField *inputInfo = alertController.textFields.firstObject;
        if (inputInfo.text.length == 0) {
            ShowMessage(@"分类名不能为空!");
            return ;
        }else{

            NSDictionary* arg = @{@"ince":@"addshopcate",
                                  @"sid":[UserModel sharedInstanced].ru_Id,
                                  @"shopcate":inputInfo.text
                                  };
            [NetRepositories addStore:arg complete:^(EnumNetResponse react, id obj, NSString *message) {
                
                ShowMessage(message);
                self.page.pageIndex = 1;
                [self queryData];
                
            }];
            
            
        }
        
    }];
    
    
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];

    [self presentViewController:alertController animated:true completion:nil];
    
}

-(void)creatSubViews{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,  CGRectGetHeight(self.view.frame) -NAVGATIONBAR_HEIGHT) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
    
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
}

#pragma mark =====================================================  Data Source
-(void)queryData{
    
    NSDictionary* arg = @{@"ince":@"addshopcate",
                          @"sid":[UserModel sharedInstanced].ru_Id,
                          @"page":[WMHelper integerConvertToString:self.page.pageIndex]
                          };
    NetRepositories* repositories = [[NetRepositories alloc]init];
    [repositories queryStore:arg page:self.page complete:^(EnumNetResponse react, NSArray *list, NSString *message, NSDictionary *mainDict) {
        if(self.page.pageIndex == 1){
            [self.dataArray removeAllObjects];
        }
        if(react == NetResponseSuccess){
            [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [self.dataArray addObject:obj];
            }];
        }else if(react == NetResponseException){
            [self alertHUD:message];
        }else{
            [self alertHUD:message];
        }
        
        [self.tableView reloadData];
        if(self.page.pageCount<=self.page.pageIndex){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        if(self.page.pageIndex==1){
            [self.tableView.mj_header endRefreshing];
        }
        
    }];
    
}
-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page.pageIndex = 1;
        [weakSelf queryData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.page.pageIndex ++;
        [weakSelf queryData];
    }];
    [self.tableView.mj_header beginRefreshing];
}




#pragma mark - ******* tableview代理方法 *******
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString *cellID = @"CELL_ID";
    
    ShopListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if(!cell){
        cell = [[ShopListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    MStore *model = self.dataArray[indexPath.row];
    cell.entity = model;
    cell.deleteBtnBlock = ^{
       
        UIAlertController *alt = [UIAlertController alertControllerWithTitle:@"确定删除该分类吗?" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            NSDictionary* arg = @{@"ince":@"deleshopcate",
                                  @"sid":[UserModel sharedInstanced].ru_Id,
                                  @"scid":model.stroe_id
                                  };
            [NetRepositories deleteStore:arg complete:^(EnumNetResponse react, id obj, NSString *message) {
                
                ShowMessage(message);
                self.page.pageIndex = 1;
                [self queryData];
            }];
            
        }];
        
        
        [alt addAction:cancelAction];
        [alt addAction:okAction];
        [self presentViewController:alt animated:YES completion:nil];
        
    };
    return cell;
    
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}





-(NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

-(NetPage *)page{
    if(!_page){
        _page = [[NetPage alloc]init];
        _page.pageIndex = 1;
    }
    return _page;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
